package Autodesk;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import DatabaseManaging.DatabaseChecker;



	public class CheckWebservice {
		
		public String writeProductLine(String nameProduct,String abProduct,String nameVersion,String abVersion,String id){
			generateAbbreviations(abProduct);
			StringBuffer stbuffer=new StringBuffer();
			String product=id+"\t"+nameProduct+"\t"+generateAbbreviations(abProduct);
			if(nameVersion.equals("") && abVersion.equals("")){
				//System.out.println("AUTOCOMPLETE al producto "+nameProduct);
				nameVersion="all";
				abVersion="all";
			}else if(abVersion.equals("") || !(getYear(abVersion).equals(abVersion)) ){
				abVersion=getYear(nameVersion);
			}else if(nameVersion.equals("all")){
				abVersion="all"; 
			}
			String release=nameVersion+"\t"+abVersion+"\t"+""+"\t"+"";
			stbuffer.append(product+release);
			return stbuffer.toString();
		}

		public String generateAbbreviations(String abProduct) {
			String abfinal="";
			String[] abRecord=abProduct.split("\t");
			int i;
			for(i=0;i<abRecord.length;i++){
				abfinal=abfinal+abRecord[i]+"\t";
			}
			for(int g=i;g<5;g++){
				abfinal=abfinal+""+"\t";

			}
			return abfinal;
		}
		
		private String writeDefaultLine(String value,String languageAbbr){
			String lang="\t"+value+"\t"+languageAbbr;
		//	String lang=ht.get("l")+"\t"+language; LOOK WHEN INSERT
			return lang;
		}
		private void writeArchive(String line,BufferedWriter fWriter) throws IOException{
			fWriter.write(line.toString());
			fWriter.write("\n");
		}

		private static void writeErrorsAddList(
				BufferedWriter foutNotFound, HashMap<String, String> ht,
				CheckWebservice checker, String stbuffer, String[] record,ArrayList<String> parcialList)
				throws IOException {
			if (ht.get("e") == null) {
				//System.out.println(stbuffer);
				parcialList.add(stbuffer);
			} else {
				System.out.println("Write the line that we could NOT find in the text document "	+ record[0]);
				checker.writeArchive(record[0], foutNotFound);
			}
		}
		
		private static boolean areEqualsProducts(String st1,String st2){
			boolean result=false;
			String [] record1=st1.split("\t");
			String [] record2=st2.split("\t");
			if(record1.length>6 & record2.length>6){			
				if(record1[1].equals(record2[1]) & getYear(record1[7]).equals(getYear(record2[7]))){
					result=true;
				}
			}else{
				if(record1[1].equals(record2[1]) & record1[8].equals(record2[8])){
					//System.out.println("REPEATED!!!!");
					result=true;
				}
			}
			return result;
		}
		private static boolean areEquals(String st1,String st2){
			boolean result=false;
			String [] record1=st1.split("\t");
			String [] record2=st2.split("\t");
			//System.out.println(record1[1]+"------------"+record2[1]);
			if(record1[1].equals(record2[1])){
				result=true;
			}
			return result;
		}
//		public HashMap<String, String> generateMapAbbreviations(
//				ArrayList<String> listRaw2) {
//			HashMap<String, String> mapAbbr = new HashMap<String, String>();
//			HashSet<String> listAbs = new HashSet();
//			ArrayList<String> listRaw = new ArrayList<String>();
//			listRaw=(ArrayList<String>)listRaw2.clone();
//			
//			String name;
//			String abb;
//			String[] record1;
//			int i;
//			for (i = 0; i < listRaw.size(); ++i) {
//				abb = "";
//				record1 = listRaw.get(i).split("\t");
//				name = record1[1];
//
//				if (!record1[2].equals("")) {
//					listAbs.add(record1[2]);
//				}
//				for (int f = i + 1; f < listRaw.size(); ++f) {
//					String[] record2 = listRaw.get(f).split("\t");
//					if (name.equals(record2[1])){
//						if (!record2[2].equals("") & !listAbs.contains(record2[2])) {
//							listAbs.add(record2[2]);
//						}
//						listRaw.remove(f);
//
//					}
//
//				}
//				if (!listAbs.isEmpty()) {
//					String absSaved=mapAbbr.get(name);
//					HashSet<String> listAbsMap = new HashSet();
//					if(absSaved!=null){
//						String[] recordSaved = absSaved.split("\t");
//						for(int h=0;h<recordSaved.length;++h){
//							listAbsMap.add(recordSaved[h]);
//						}
//						Iterator it=listAbs.iterator();	
//						while(it.hasNext()){
//							listAbsMap.add((String)it.next());
//						}
//						it=listAbsMap.iterator();
//						while(it.hasNext()){
//							abb = abb + it.next() + "\t";
//						}
//					}else{
//						Iterator it=listAbs.iterator();	
//						while(it.hasNext()){
//							abb = abb + it.next() + "\t";
//						}
//
//					}
//					mapAbbr.put(name, abb);
//					listAbsMap.clear();
//					
//				}
//				listAbs.clear();
//			}
//
//			return mapAbbr;
//		}
//		
//		private ArrayList<String> generateListWithoutRepeations(ArrayList<String> listRaw,String param){
//			ArrayList<String> result=new ArrayList<String>();
//			int i;
//			for(i=0;i<listRaw.size();i++){
//
//				for(int f=i+1;f<listRaw.size();f++){
//					if("products".equals(param)|| "products".equals(param)){
//						if(areEqualsProducts(listRaw.get(i), listRaw.get(f))){
//							listRaw.remove(f);
//						}
//					}else{
//						if(areEquals(listRaw.get(i), listRaw.get(f))){
//							listRaw.remove(f);
//						}
//					}
//				}
//				result.add(listRaw.get(i));
//			}
//////			if(i==listRaw.size()-1){
//////				result.add(listRaw.get(i));
//////			}
//			return result;
//		}
//	
//	private ArrayList<String> generateFinalList(ArrayList<String> list,HashMap<String, String> mapAbbr,String param){
//		String resultReg;
//		ArrayList<String> result=new ArrayList<String>();
//		for(int i=0;i<list.size();i++){
//			resultReg = generateRegToDatabase(list, param, i,mapAbbr);
//			result.add(resultReg);
//		}
//		return result;
//	}
//	private ArrayList<String> checkNotRepeatedBaseline(ArrayList<String> listRaw,String param){
//		ArrayList<String> result=new ArrayList<String>();
//		ArrayList<String> halfResult=new ArrayList<String>();
//		HashMap<String, String> mapAbbr=new HashMap<String, String>();
//		
//		//System.out.println("Length1: "+listRaw.size());
//		
//		mapAbbr=generateMapAbbreviations(listRaw);
//		
//		//System.out.println("Length2: "+listRaw.size()+" HashMap "+mapAbbr);
//		
//		halfResult=generateListWithoutRepeations(listRaw,param);
//		
//		//System.out.println(halfResult+ "Length: "+listRaw.size());
//		
//		result=generateFinalList(halfResult, mapAbbr,param);
//		
//		return result;
//	}
//
//	private String generateRegToDatabase(ArrayList<String> listRaw,
//			String param, int i, HashMap<String, String> mapAbbr) {
//		String[] recordToAdd = listRaw.get(i).split("\t");
//		String abbr = "";
//		String resultReg = null;
//		abbr = mapAbbr.get(recordToAdd[1]);
//		if (abbr == null) {
//			abbr = "";
//		}
//		if (param.equals("product") || param.equals("products")) {
//			resultReg = writeProductLine(recordToAdd[1], abbr, recordToAdd[7],
//					recordToAdd[8],"");
//		} else {
//			resultReg = writeDefaultLine(recordToAdd[1], abbr);
//		}
//
//		return resultReg;
//	}
		private static String getYear(String value){
			String year="";
			Pattern yearPattern = Pattern
					.compile("20[0-9][0-9]");
			Matcher yearMatcher = yearPattern.matcher(value);
			year = yearMatcher.find() ? yearMatcher.group() : value;
			return year;
		}
//
//		private static boolean containsYear(String value){
//			boolean year;
//			Pattern yearPattern = Pattern
//					.compile("20[0-9][0-9]");
//			Matcher yearMatcher = yearPattern.matcher(value);
//			year = yearMatcher.find() ? true : false;
//			return year;
//		}
//		
//		private void writeArchiveFromList(BufferedWriter fout, ArrayList<String> parciaList) throws IOException{
//			for(int i=0;i<parciaList.size();i++){
//				fout.write(parciaList.get(i).toString());
//				fout.write("\n");
//			}
//		}
//		
//		private static String manageBaselineValue(CheckWebservice checker,
//				HashMap<String, String> ht, String stbuffer, String[] record,String product) {
//			if (ht.get("e") == null) {
//				System.out.println(record[2]);
//				if(containsYear(record[2])){
//					stbuffer=checker.writeProductLine(ht.get("p"),product, record[2], "","");
//				}else{
//					stbuffer=checker.writeProductLine(ht.get("p"),product, "all", "","");
//				}
//			} else {
//				record[0] = product + "\t" + record[2];// Prepare the string for being stored
//			}
//			return stbuffer;
//		}
//		
//	public static void main(String[] args) {
//		DatabaseChecker dbchecker= new DatabaseChecker();
//		BufferedReader fis,fisMapDoc; BufferedWriter fout, foutNotFound;
//		CheckWebservice checker = new CheckWebservice();
//		WebservReader webReader = new WebservReader();
//		HashMap<String, String> ht = new HashMap<String, String>();
//		String param = args[3].toLowerCase();
//		String pattern = null;
//		String stbuffer = null;
//		ArrayList<String> parciaList=new ArrayList<String>();
//		try {
//			System.out.println("Starting...");
//			fis = new BufferedReader(new FileReader(args[0]));
//			fout = new BufferedWriter(new FileWriter(args[1]));
//			foutNotFound = new BufferedWriter(new FileWriter(args[2]));
//			File mappingFile = new File(args[4]);
//			pattern = fis.readLine();//LOOK AT IT
//			while ((pattern = fis.readLine()) != null) {
//				//pattern = checker.validBlankError( pattern,fis);
//				String record[] = pattern.split("\t");
//				ht.put("e",null);
//				if ("product".equals(param) || "products".equals(param)) {
//					if("".equals(record[0])){ 
//						ht = webReader.readXml(record[1], record[2], "", param);
//						if (ht.get("e") == null) {
//							if(!getYear(ht.get("r")).equals("")){
//								stbuffer = checker.writeProductLine(ht.get("p"), record[1],ht.get("r"),getYear(ht.get("r")),"");
//							}else{								
//								stbuffer = checker.writeProductLine(ht.get("p"), record[1],ht.get("r"),record[2],"");
//							}
//						} else {
//							ht = webReader.readXml(record[1],"all","", param);
//							if(ht.get("e")==null){
//								stbuffer =checker.writeProductLine(ht.get("p"), record[1],"all","all",""); //In this case, the webservice does have the product abbreviation stored but doesn't have the release abbreviation stored
//							}else{
//								ht = webReader.readXml("","all",record[1], param); //In this case the baseline web service posseses the abbreviation
//								stbuffer = manageBaselineValue(checker, ht, stbuffer,
//										record,record[1]);
//							}
//						}
//						
//					}else{
//						ht = webReader.readXml("","all",record[0], param);
//						stbuffer = manageBaselineValue(checker, ht, stbuffer,
//								record,record[0]);
//					}
//				} else {//Language or channels
//					ht = webReader.readXml("", "", record[0], param);
//					if (ht.get("e") == null) {
//						stbuffer = checker.writeDefaultLine(ht.get("d"), record[0]);
//					}else{
//						stbuffer = checker.writeDefaultLine(record[0], "");
//					}
//				}
//				writeErrorsAddList(foutNotFound, ht, checker, stbuffer, record,parciaList);
//			}
//			System.out.println(parciaList);
//			System.out.println("Verifyng not to have repeated information..");
//			parciaList=checker.checkNotRepeatedBaseline(parciaList, param);
//			System.out.println(parciaList);
//			System.out.println("Checking not repeated information with the database..");
//			if(param.equals("products") || param.equals("product")){
//				dbchecker.findExistenceDatabase(parciaList,mappingFile,checker);
//			}
//			System.out.println(parciaList);
//			System.out.println("Writting..");
//			checker.writeArchiveFromList(fout, parciaList);
//			
//			fout.close();
//			foutNotFound.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		System.out.println("Finished.");
//	}
//	
	}
